import { u64, i64, u16, REGISTER_COUNT, SEGMENT_REGISTER_COUNT, XMM_REGISTER_COUNT, XMM_REGISTER_SIZE, Registers as RegisterEnum, SegmentRegisters, toU64, toI64 } from '../types';

export class RegisterManager {
  private generalRegisters: u64[];  // 通用寄存器 (RAX, RBX, RCX, RDX, etc.)
  private segmentRegisters: u16[];  // 段寄存器 (CS, DS, ES, SS, FS, GS)
  private xmmRegisters: Uint8Array[];  // XMM寄存器 (128位)
  private instructionPointer: u64;  // 指令指针 (RIP)
  private stackPointer: u64;  // 栈指针 (RSP) - 这里也可以通过generalRegisters[RSP]访问
  private framePointer: u64;  // 帧指针 (RBP) - 同上
  private xcr0: u64;  // XCR0寄存器，用于XGETBV/XSETBV指令
  private cr0: u64;  // CR0控制寄存器，用于控制处理器的操作模式和特性
  
  // 标志寄存器
  private flags = {
    CF: false,  // 进位标志
    PF: false,  // 奇偶标志
    AF: false,  // 辅助进位标志
    ZF: false,  // 零标志
    SF: false,  // 符号标志
    TF: false,  // 陷阱标志
    IF: false,  // 中断允许标志
    DF: false,  // 方向标志
    OF: false,  // 溢出标志
    IOPL: 0,    // I/O特权级别
    NT: false,  // 嵌套任务标志
    RF: false,  // 恢复标志
    VM: false,  // 虚拟8086模式标志
    AC: false,  // 对齐检查标志
    VIF: false, // 虚拟中断标志
    VIP: false, // 虚拟中断挂起标志
    ID: false   // ID标志
  };
  
  // 标志位类型
  private FlagType: Record<string, keyof typeof this.flags> = {
    CF: 'CF',
    PF: 'PF',
    AF: 'AF',
    ZF: 'ZF',
    SF: 'SF',
    TF: 'TF',
    IF: 'IF',
    DF: 'DF',
    OF: 'OF',
    IOPL: 'IOPL',
    NT: 'NT',
    RF: 'RF',
    VM: 'VM',
    AC: 'AC',
    VIF: 'VIF',
    VIP: 'VIP',
    ID: 'ID'
  };

  constructor() {
    // 初始化通用寄存器
    this.generalRegisters = new Array(REGISTER_COUNT).fill(0n);
    
    // 初始化段寄存器
    this.segmentRegisters = new Array(SEGMENT_REGISTER_COUNT).fill(0);
    
    // 初始化XMM寄存器
    this.xmmRegisters = [];
    for (let i = 0; i < XMM_REGISTER_COUNT; i++) {
      this.xmmRegisters.push(new Uint8Array(XMM_REGISTER_SIZE));
    }
    
    // 重置指令指针、栈指针和帧指针
    this.instructionPointer = 0n;
    this.stackPointer = 0n;
    this.framePointer = 0n;
    this.xcr0 = 0n;  // 初始化XCR0寄存器
    this.cr0 = 0n;  // 初始化CR0寄存器
    this.cr0 = 0n;  // 初始化CR0寄存器
    
    // 初始化标志寄存器
    this.flags = {
      CF: false,
      PF: false,
      AF: false,
      ZF: false,
      SF: false,
      TF: false,
      IF: false,
      DF: false,
      OF: false,
      IOPL: 0,
      NT: false,
      RF: false,
      VM: false,
      AC: false,
      VIF: false,
      VIP: false,
      ID: false
    };
  }

  // 获取通用寄存器值
  getRegister(reg: RegisterEnum): u64 {
    return this.generalRegisters[reg];
  }

  // 设置通用寄存器值
  setRegister(reg: RegisterEnum, value: u64): void {
    this.generalRegisters[reg] = toU64(Number(value));
    
    // 更新栈指针和帧指针的缓存
    if (reg === RegisterEnum.RSP) {
      this.stackPointer = this.generalRegisters[reg];
    } else if (reg === RegisterEnum.RBP) {
      this.framePointer = this.generalRegisters[reg];
    }
  }

  // 获取段寄存器值
  getSegmentRegister(seg: SegmentRegisters): u16 {
    return this.segmentRegisters[seg];
  }

  // 设置段寄存器值
  setSegmentRegister(seg: SegmentRegisters, value: u16): void {
    this.segmentRegisters[seg] = value;
  }

  // 获取XMM寄存器值
  getXmmRegister(index: number): Uint8Array {
    if (index < 0 || index >= XMM_REGISTER_COUNT) {
      throw new Error(`Invalid XMM register index: ${index}`);
    }
    return this.xmmRegisters[index].slice();
  }

  // 设置XMM寄存器值
  setXmmRegister(index: number, value: Uint8Array): void {
    if (index < 0 || index >= XMM_REGISTER_COUNT) {
      throw new Error(`Invalid XMM register index: ${index}`);
    }
    if (value.length !== XMM_REGISTER_SIZE) {
      throw new Error(`Invalid XMM register value size: ${value.length}, expected ${XMM_REGISTER_SIZE}`);
    }
    this.xmmRegisters[index].set(value);
  }

  // 获取指令指针
  getInstructionPointer(): u64 {
    return this.instructionPointer;
  }

  // 设置指令指针
  setInstructionPointer(value: u64): void {
    this.instructionPointer = toU64(Number(value));
  }

  // 获取栈指针
  getStackPointer(): u64 {
    return this.stackPointer;
  }

  // 设置栈指针
  setStackPointer(value: u64): void {
    this.stackPointer = toU64(Number(value));
    this.generalRegisters[RegisterEnum.RSP] = this.stackPointer;
  }

  // 获取帧指针
  getFramePointer(): u64 {
    return this.framePointer;
  }

  // 设置帧指针
  setFramePointer(value: u64): void {
    this.framePointer = toU64(Number(value));
    this.generalRegisters[RegisterEnum.RBP] = this.framePointer;
  }

  // 获取XCR0寄存器值
  getXcr0(): u64 {
    return this.xcr0;
  }

  // 设置XCR0寄存器值
  setXcr0(value: u64): void {
    this.xcr0 = toU64(Number(value));
  }

  // 获取CR0寄存器值
  getCr0(): u64 {
    return this.cr0;
  }

  // 设置CR0寄存器值
  setCr0(value: u64): void {
    this.cr0 = toU64(Number(value));
  }

  // 获取当前特权级 (CPL)
  getCurrentPrivilegeLevel(): number {
    // CPL是CS段寄存器的低2位
    const cs = this.segmentRegisters[SegmentRegisters.CS];
    return cs & 3; // 返回0-3的特权级
  }

  // 获取标志位
  getFlag(flag: string): boolean {
    if (flag === 'IOPL') {
      return this.flags[flag as 'IOPL'] > 0;
    }
    return this.flags[flag as keyof typeof this.flags] as boolean;
  }

  // 设置标志位
  setFlag(flag: string, value: boolean): void {
    if (flag === 'IOPL') {
      this.flags[flag as 'IOPL'] = value ? 3 : 0;
    } else {
      (this.flags[flag as keyof typeof this.flags] as boolean) = value;
    }
  }

  // 获取标志寄存器的数值表示
  getFlagsRegister(): u64 {
    let flags = 0n;
    
    flags |= BigInt(this.flags.CF ? 1 : 0) << 0n;
    flags |= BigInt(this.flags.PF ? 1 : 0) << 2n;
    flags |= BigInt(this.flags.AF ? 1 : 0) << 4n;
    flags |= BigInt(this.flags.ZF ? 1 : 0) << 6n;
    flags |= BigInt(this.flags.SF ? 1 : 0) << 7n;
    flags |= BigInt(this.flags.TF ? 1 : 0) << 8n;
    flags |= BigInt(this.flags.IF ? 1 : 0) << 9n;
    flags |= BigInt(this.flags.DF ? 1 : 0) << 10n;
    flags |= BigInt(this.flags.OF ? 1 : 0) << 11n;
    flags |= BigInt(this.flags.IOPL) << 12n;
    flags |= BigInt(this.flags.NT ? 1 : 0) << 14n;
    flags |= BigInt(this.flags.RF ? 1 : 0) << 16n;
    flags |= BigInt(this.flags.VM ? 1 : 0) << 17n;
    flags |= BigInt(this.flags.AC ? 1 : 0) << 18n;
    flags |= BigInt(this.flags.VIF ? 1 : 0) << 19n;
    flags |= BigInt(this.flags.VIP ? 1 : 0) << 20n;
    flags |= BigInt(this.flags.ID ? 1 : 0) << 21n;
    
    return flags;
  }

  // 设置标志寄存器的数值表示
  setFlagsRegister(value: u64): void {
    this.flags.CF = Boolean(value & (1n << 0n));
    this.flags.PF = Boolean(value & (1n << 2n));
    this.flags.AF = Boolean(value & (1n << 4n));
    this.flags.ZF = Boolean(value & (1n << 6n));
    this.flags.SF = Boolean(value & (1n << 7n));
    this.flags.TF = Boolean(value & (1n << 8n));
    this.flags.IF = Boolean(value & (1n << 9n));
    this.flags.DF = Boolean(value & (1n << 10n));
    this.flags.OF = Boolean(value & (1n << 11n));
    this.flags.IOPL = Number((value >> 12n) & 3n);
    this.flags.NT = Boolean(value & (1n << 14n));
    this.flags.RF = Boolean(value & (1n << 16n));
    this.flags.VM = Boolean(value & (1n << 17n));
    this.flags.AC = Boolean(value & (1n << 18n));
    this.flags.VIF = Boolean(value & (1n << 19n));
    this.flags.VIP = Boolean(value & (1n << 20n));
    this.flags.ID = Boolean(value & (1n << 21n));
  }

  // 重置所有寄存器
  reset(): void {
    // 重置通用寄存器
    for (let i = 0; i < REGISTER_COUNT; i++) {
      this.generalRegisters[i] = 0n;
    }
    
    // 重置段寄存器
    for (let i = 0; i < SEGMENT_REGISTER_COUNT; i++) {
      this.segmentRegisters[i] = 0;
    }
    
    // 重置XMM寄存器
    for (let i = 0; i < XMM_REGISTER_COUNT; i++) {
      this.xmmRegisters[i].fill(0);
    }
    
    // 重置指令指针、栈指针和帧指针
    this.instructionPointer = 0n;
    this.stackPointer = 0n;
    this.framePointer = 0n;
    
    // 重置标志寄存器
    this.flags = {
      CF: false,
      PF: false,
      AF: false,
      ZF: false,
      SF: false,
      TF: false,
      IF: false,
      DF: false,
      OF: false,
      IOPL: 0,
      NT: false,
      RF: false,
      VM: false,
      AC: false,
      VIF: false,
      VIP: false,
      ID: false
    };
  }

  // 打印寄存器状态（调试用）
  printState(): void {
    console.log('Register State:');
    
    // 打印通用寄存器
    console.log('General Registers:');
    Object.entries(RegisterEnum).forEach(([name, index]) => {
      if (typeof index === 'number') {
        console.log(`  ${name}: 0x${this.generalRegisters[index].toString(16).padStart(16, '0')}`);
      }
    });
    
    // 打印段寄存器
    console.log('Segment Registers:');
    Object.entries(SegmentRegisters).forEach(([name, index]) => {
      if (typeof index === 'number') {
        console.log(`  ${name}: 0x${this.segmentRegisters[index].toString(16).padStart(4, '0')}`);
      }
    });
    
    // 打印特殊寄存器
    console.log('Special Registers:');
    console.log(`  RIP: 0x${this.instructionPointer.toString(16).padStart(16, '0')}`);
    console.log(`  RSP: 0x${this.stackPointer.toString(16).padStart(16, '0')}`);
    console.log(`  RBP: 0x${this.framePointer.toString(16).padStart(16, '0')}`);
    console.log(`  CR0: 0x${this.cr0.toString(16).padStart(16, '0')}`);
    console.log(`  CPL: ${this.getCurrentPrivilegeLevel()}`);
    
    // 打印标志寄存器
    console.log('Flags:');
    Object.entries(this.flags).forEach(([name, value]) => {
      console.log(`  ${name}: ${value}`);
    });
  }
}